import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class OkHttpDemo {
    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws Exception {
        sendGetRequestSync("http://localhost:8801", null);
        sendGetRequestAsync("http://localhost:8801", null);
        sendPostRequest("http://localhost:8801", null);
    }

    /**
     * 使用get请求同步请求一个地址
     *
     * @param url        请求的地址
     * @param parameters 请求的参数
     */
    private static void sendGetRequestSync(String url, Map<String, String> parameters) throws Exception {
        String queryParameterString = "";
        if (parameters != null) {
            queryParameterString += "?";
            for (String key : parameters.keySet()) {
                queryParameterString += key + "&" + parameters.get(key);
            }
        }
        Request request = new Request.Builder()
                .url(url + queryParameterString)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful())
                throw new IOException("错误代码:" + response);
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ":" + responseHeaders.value(i));
            }
            System.out.println(response.body().string());
        }
    }

    /**
     * 使用get请求异步请求一个地址
     *
     * @param url        请求的地址
     * @param parameters 请求的参数
     */
    private static void sendGetRequestAsync(String url, Map<String, String> parameters) {
        String queryParameterString = "";
        if (parameters != null) {
            queryParameterString += "?";
            for (String key : parameters.keySet()) {
                queryParameterString += key + "&" + parameters.get(key);
            }
        }
        Request request = new Request.Builder()
                .url(url + queryParameterString)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful())
                        throw new IOException("错误代码:" + response);
                    Headers responseHeaders = response.headers();
                    for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                    }

                    System.out.println(responseBody.string());
                }
            }
        });
    }

    /**
     * 使用post请求请求一个地址
     *
     * @param url        请求的地址
     * @param parameters 请求的参数
     * @throws Exception
     */
    private static void sendPostRequest(String url, Map<String, String> parameters) throws Exception {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        if (parameters != null) {
            for (String key : parameters.keySet()) {
                formBodyBuilder.add(key, parameters.get(key));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(formBodyBuilder.build())
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful())
                throw new IOException("错误代码:" + response);
            System.out.println(response.body().string());
        }

    }
}
